<?php

declare(strict_types=1);

namespace app\model;

use think\facade\Db;
use think\facade\Log;

/**
 *
 *
 * @mixin \think\Model
 * @property int $channel_id 渠道id
 * @property bool $serv_type 业务类型。详见代码里的constant->PRODUCT_SERV_TYPE
 * @property float $value 折扣，比如：99.82折
 * @property bool $sub_type 子业务类型  1慢充 2快充
 * @property bool $state 状态 1启用  2禁用
 * @property string $created_at
 * @property string $updated_at
 * @property-read \app\model\ServiceSub $sub
 * @property-read string $name
 * @property-read mixed $sub_tab
 * @property-read \app\model\AgentChannel $agentChannel
 * @property-read \app\model\AgentChannel $agent_channel
 * @property-read mixed $permit_status
 */
class ChannelServDiscount extends CommonModel
{


    protected $append = [
        'permit_status'
    ];

    const STATUS_ACTIVE = 1;


    const STATE_AVTIVE = 1;
    const STATE_STOP = 2;

    const STATE_NO_SERVE = 3;//不入库，置灰

    // 子业务配置名称
    public function sub()
    {
        return $this->hasOne(ServiceSub::class, 'serv_type', 'serv_type');
    }

    public function agentChannel()
    {
        return $this->hasOne(AgentChannel::class, 'id', 'channel_id');
    }

    /**
     * h5 菜单名称
     * @param $name
     * @param $params
     * @return string
     */
    public function getNameAttr($name, $params)
    {
        $serv_type = $params['serv_type'] ?? '';

        if (empty($serv_type)) return '未知';

        $datas = PRODUCT_SERV_TYPE[$serv_type] ?? '';

        return $datas['shortName'] ?? ($datas['name'] ?? '');

    }

    public function getPermitStatusAttr($name, $params)
    {


        $serv_types = AgentServiceConfig::query()
            ->where('agent_id', $this->agentChannel->agent_id)
            ->where('status', AgentServiceConfig::STATUS_ACTIVE)
//            ->cache('getPermitStatusAttr' . $this->agentChannel->agent_id)
            ->column('serv_type');

        if (in_array($this->serv_type, $serv_types) !== false) {
            return AgentServiceConfig::STATUS_ACTIVE;
        } else {
            return AgentServiceConfig::STATUS_STOP;
        }

    }

    /**
     * 获取筛选的按钮
     * @param  $name
     */
    public function getSubTabAttr($name, $params)
    {

        $serv_type = $params['serv_type'];


        switch ($serv_type) {
            case PRODUCT_COUPON_SERV:
                return [
                    [
                        'name' => '全部',
                        'value' => ''
                    ],
                    [
                        'name' => '待支付',
                        'value' => 'wait_pay'
                    ],
                    [
                        'name' => '已支付',
                        'value' => 'pay'
                    ],
                    [
                        'name' => '已完成',
                        'value' => 'finish'
                    ],
                    [
                        'name' => '已退款',
                        'value' => 'refund'
                    ],
                ];
            case PRODUCT_AROUND_SHOP_SERV:
                return [
                    [
                        'name' => '全部',
                        'value' => ''
                    ],
                    [
                        'name' => '待支付',
                        'value' => 'wait_pay'
                    ],
                    [
                        'name' => '已支付',
                        'value' => 'pay'
                    ],
                    [
                        'name' => '已完成',
                        'value' => 'finish'
                    ],
                    [
                        'name' => '退款',
                        'value' => 'refund'
                    ],
                ];
            case PRODUCT_SECKILL_SERV:
            case PRODUCT_METUAN_SERV:
                return [
                    [
                        'name' => '全部',
                        'value' => ''
                    ],
                    [
                        'name' => '已支付',
                        'value' => 'pay'
                    ],
                    [
                        'name' => '已完成',
                        'value' => 'finish'
                    ],
                    [
                        'name' => '退款',
                        'value' => 'refund'
                    ],
                ];
                break;
            case PRODUCT_MOBILE_SERV:
                return [
                    [
                        'name' => '慢充',
                        'value' => 1
                    ],
                    [
                        'name' => '快充',
                        'value' => 2
                    ],

                ];
                break;
            case PRODUCT_MEAL_SERV:
                return [];
                break;
            case PRODUCT_FILM_SERV:
                return [
                    [
                        'name' => '全部',
                        'value' => 0
                    ],
                    [
                        'name' => '已出票',
                        'value' => 2
                    ],
                    [
                        'name' => '已取消',
                        'value' => 3
                    ],
                ];
                break;
            default:
                return [
                    [
                        'name' => '全部',
                        'value' => ''
                    ],
                    [
                        'name' => '已支付',
                        'value' => 'pay'
                    ],
                    [
                        'name' => '已完成',
                        'value' => 'finish'
                    ],
                    [
                        'name' => '退款',
                        'value' => 'refund'
                    ],
                ];
                break;
        }


    }


    /**
     * 获取真实的产品值，可能没有勾选供应商就不显示
     * @param $channel_id
     * @param $template_url
     * @param $agent_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRealServ($channel_id = '', $agent_id, $template_url = '')
    {

        $cacheKey = 'getRealServ' . $channel_id . $agent_id . $template_url;

        if ($cache = cache($cacheKey)) {
            return $cache;
        }

        if (empty($agent_id) && empty($template_id)) {
            $agentServiceConfig = AgentServiceConfig::query()
                ->where('status', AgentServiceConfig::STATUS_ACTIVE)
                ->where('agent_id', $agent_id)
                ->column('serv_type');
            return $agentServiceConfig;
        }


        $agentServiceConfig = AgentServiceConfig::query()
            ->where('agent_id', $agent_id)
            ->column('*', 'serv_type');

        if ($channel_id) {
            $channelServ = Db::name('channel_serv_discount')
                ->where('channel_id', $channel_id)
                ->where('state', 1)
                ->column('serv_type');
        } else {
            $template_id = Template::query()->where('pre_url', $template_url)
                ->where('status', Template::STATUS_ACTIVE)
                ->value('id');
            $channel_ids = AgentChannel::query()->where('agent_id', $agent_id)
                ->where('state', AgentChannel::STATE_ACTIVE)
                ->where('template_id', $template_id)
                ->column('id');

            $channel_ids = array_values(array_unique($channel_ids));
            $channelServ = Db::name('channel_serv_discount')
                ->where('state', 1)
                ->whereIn('channel_id', $channel_ids)
                ->column('serv_type');
        }

        $channelServ = array_values(array_unique($channelServ));

        if ($template_url) {
            $templates = Template::query()
                ->join('template_service', 'template_service.template_id = template.id')
                ->where('template.pre_url', $template_url)
                ->column('serv_type');

            foreach ($channelServ as $key => $serv) {
                if (!in_array($serv, $templates)) {
                    unset($channelServ[$key]);
                }
            }
        }
        //dd($channelServ);
        //判断是否存在供应商配置
        foreach ($channelServ as $key => $serv) {
            if (in_array($serv, [PRODUCT_MEAL_SERV, PRODUCT_MOBILE_SERV])) {
                continue;
            }

            if ($agentServiceConfig[$serv]['income_type'] == AgentServiceConfig::INCOME_TYPE_SELF && $agentServiceConfig[$serv]['time_end'] < time()) {
                Log::info('已过期');
                unset($channelServ[$key]);
            }


            if (!empty($agentServiceConfig[$serv]) && $agentServiceConfig[$serv]['income_type'] == AgentServiceConfig::INCOME_TYPE_SELF) {
                continue;
            }

            $agentSupplier = AgentSupplier::where([
                'agent_id' => $agent_id,
                'serv_type' => $serv,
            ])->find();
            if (!$agentSupplier) {
                unset($channelServ[$key]);
            }

        }

        $res = array_values($channelServ);

        cache($cacheKey, $res, 22);

        return $res;

    }

}
